﻿namespace RainbowNavBar.Function
{
    public class XmlConfigManager
    {

        private readonly string _filePath;

        public XmlConfigManager(string filePath)
        {
            _filePath = filePath;
        }

        // 加载 XML 文件
        private XDocument LoadXml()
        {
            // RemoveBomIfPresent(_filePath);
            try
            {
                return XDocument.Load(_filePath);
            }
            catch
            {
                MessageBox.Show("配置文件错误，请将文件删除后重试！", "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
                return null;
            }
        }

        // 保存 XML 文件
        private void SaveXml(XDocument doc)
        {
            doc.Save(_filePath);
        }

        #region 应用配置相关操作

        // 获取应用配置的值
        public string GetAppConfigValue(string key)
        {
            var doc = LoadXml();
            var element = doc.Descendants("AppConfig")
                             .Descendants("add")
                             .FirstOrDefault(x => (string)x.Attribute("key") == key);

            return element?.Attribute("value")?.Value;
        }

        // 设置应用配置的值
        public void SetAppConfigValue(string key, string value)
        {
            var doc = LoadXml();
            var element = doc.Descendants("AppConfig")
                             .Descendants("add")
                             .FirstOrDefault(x => (string)x.Attribute("key") == key);

            if (element != null)
            {
                element.SetAttributeValue("value", value);
            }
            else
            {
                doc.Descendants("AppConfig").FirstOrDefault()?.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
            }

            SaveXml(doc);
        }

        #endregion

        #region 存储数据相关操作

        // 获取所有数据记录
        public List<Dictionary<string, string>> GetAllDataRecords()
        {
            var doc = LoadXml();
            var records = doc.Descendants("DataRecords")
                             .Descendants("Record")
                             .Select(record =>
                                 record.Descendants("add")
                                       .ToDictionary(
                                           x => (string)x.Attribute("key"),
                                           x => (string)x.Attribute("value")
                                       )
                             ).ToList();
            return records;
        }

        // 获取所有数据记录Sync
        public static List<Dictionary<string, string>> GetAllDataRecordsSync(XDocument dc)
        {
            var doc = dc;
            var records = doc.Descendants("DataRecords")
                             .Descendants("Record")
                             .Select(record =>
                                 record.Descendants("add")
                                       .ToDictionary(
                                           x => (string)x.Attribute("key"),
                                           x => (string)x.Attribute("value")
                                       )
                             ).ToList();
            return records;
        }

        // 获取某条数据记录
        public Dictionary<string, string> GetDataRecordByTagName(string tagName)
        {
            var doc = LoadXml();
            var record = doc.Descendants("DataRecords")
                            .Descendants("Record")
                            .FirstOrDefault(r => r.Descendants("add")
                                                  .Any(a => (string)a.Attribute("key") == "TagName" && (string)a.Attribute("value") == tagName));

            if (record != null)
            {
                return record.Descendants("add")
                             .ToDictionary(
                                 x => (string)x.Attribute("key"),
                                 x => (string)x.Attribute("value")
                             );
            }

            return null;
        }

        // 添加一条数据记录
        public void AddDataRecord(Dictionary<string, string> data)
        {
            var doc = LoadXml();
            XElement newRecord = new XElement("Record");

            foreach (var item in data)
            {
                newRecord.Add(new XElement("add", new XAttribute("key", item.Key), new XAttribute("value", item.Value)));
            }

            doc.Descendants("DataRecords").FirstOrDefault()?.Add(newRecord);
            SaveXml(doc);
        }

        // 删除某条数据记录
        public void DeleteDataRecord(string tagName)
        {
            var doc = LoadXml();
            var recordToRemove = doc.Descendants("DataRecords")
                                    .Descendants("Record")
                                    .FirstOrDefault(r => r.Descendants("add")
                                                          .Any(a => (string)a.Attribute("key") == "TagName" && (string)a.Attribute("value") == tagName));

            if (recordToRemove != null)
            {
                recordToRemove.Remove();
                SaveXml(doc);
            }
        }

        // 更新某条数据记录
        public void UpdateDataRecord(string tagName, Dictionary<string, string> updatedData)
        {
            var doc = LoadXml();
            var recordToUpdate = doc.Descendants("DataRecords")
                                    .Descendants("Record")
                                    .FirstOrDefault(r => r.Descendants("add")
                                                          .Any(a => (string)a.Attribute("key") == "TagName" && (string)a.Attribute("value") == tagName));

            if (recordToUpdate != null)
            {
                foreach (var item in updatedData)
                {
                    var element = recordToUpdate.Descendants("add")
                                                .FirstOrDefault(x => (string)x.Attribute("key") == item.Key);

                    if (element != null)
                    {
                        element.SetAttributeValue("value", item.Value);
                    }
                    else
                    {
                        recordToUpdate.Add(new XElement("add", new XAttribute("key", item.Key), new XAttribute("value", item.Value)));
                    }
                }

                SaveXml(doc);
            }
        }

        #endregion
    }
}
